<?php

/**
 * 文件说明.
 * 
 * @author Kun Xu <kunx@jumei.com>
 */
class UpyunController extends Controller
{

    public $layout = '//layouts/column2';
    public $navbarTitle = '用户上传';
    public $menu;

    public function beforeAction()
    {
        $this->menu = array(
            array('label' => '前台'),
            array('label' => '上传文件', 'icon' => 'icon-arrow-up', 'url' => Yii::app()->createUrl($this->id . '/forms'), 'active' => true),
//            array('label' => 'Profile', 'icon' => 'user', 'url' => '#'),
//            array('label' => 'Settings', 'icon' => 'cog', 'url' => '#'),
//            array('label' => 'Help', 'icon' => 'flag', 'url' => '#'),
            '-----',
            array('label' => '后台'),
            array('label' => '文件列表', 'icon' => 'cog', 'url' => Yii::app()->createUrl('admin/upyunadmin/list')),
//            array('label' => 'Library', 'icon' => 'book', 'url' => '#'),
//            array('label' => 'Application', 'icon' => 'pencil', 'url' => '#'),
        );
        return true;
    }

    public function actionForms()
    {
        // 空间名
        $bucket = 'xkdemo';
//        $bucket = 'xkfiles';
        // 表单 API 验证密匙：需要访问又拍云管理后台的空间管理页面获取
        $form_api_secret = '/W87HTBsR4SClO+QLNnmuM8VGMk=';
//        $form_api_secret = 'MTHGL3ymd0NwSv3UIrXgQRn405k=';


        $options = array();
        $options['bucket'] = $bucket;

        // 授权过期时间：以页面加载完毕开始计时，10分钟内有效
        $options['expiration'] = time() + 600;

        // 保存路径：最终将以"/年/月/日/upload_待上传文件名"的形式进行保存
        /**
         * 绝对值	用户自定义	写死的内容，如: /dir/filename
          时间类	{year} {mon} {day} {hour} {min} {sec}	日期、时间相关内容
          md5类	{filemd5}	文件内容的 md5 值
          随机类	{random} {random32}	16 位或 32 位随机字符和数字
          文件名	{filename} {suffix} {.suffix}	上传文件的文件名及扩展名
         */
        $options['save-key'] = '/{year}/{mon}/{day}/upload_{filename}{.suffix}';

        // 文件类型限制：仅允许上传扩展名为 jpg,gif,png 三种类型的文件
//        $options['allow-file-type'] = 'jpg,gif,png';
        // 图片宽度限制：仅允许上传宽度在 0～1024px 范围的图片文件
        //$options['image-width-range'] = '0,1024';
        // 图片高度限制：仅允许上传高度在 0～1024px 范围的图片文件
        //$options['image-height-range'] = '0,1024';
        // 同步跳转 url：表单上传完成后，使用 http 302 的方式跳转到该 URL
        $options['return-url'] = 'http://127.0.0.1:1000/y1/index.php/upyun/return/bucket/' . $bucket . '/user_id/2';
        // 异步回调 url：表单上传完成后，云存储服务端主动把上传结果 POST 到该 URL
        // 请注意该地址必须公网可以正常访问
        // $options['notify-url'] = 'http://www.demobucket.com/notify.php'; 
//         $options['notify-url'] = 'http://127.0.0.1:1000/y1/index.php/upyun/return/user_id/2';//必须公网可见
        // 缩略类型：固定宽度和高度，若宽高不足时进行拉伸
        $options['x-gmkerl-type'] = 'fix_both';

        // 保证最终的图片宽高为 200*160
//        $options['x-gmkerl-value'] = '200x160';
        // 计算 policy 内容，具体说明请参阅"Policy 内容详解"
        $policy = base64_encode(json_encode($options));

        // 计算签名值，具体说明请参阅"Signature 签名"
        $signature = md5($policy . '&' . $form_api_secret);
        $data = array(
            'bucket' => $bucket,
            'policy' => $policy,
            'signature' => $signature,
        );
//        $this->renderPartial('forms', $data);
        $this->render('forms', $data);
    }

    /**
     * 获取空间使用情况
     * @param string $bucket
     */
    public function actionGetBucketUsage($bucket = 'xkdemo')
    {
        $bucketname = $bucket;
        $username = 'xukun';
        $password = 'xukuntest';
        Yii::import('ext.UpYun');
        $upYun = new UpYun($bucketname, $username, $password);
        $usage = $upYun->getBucketUsage(); //获取空间使用字节
        var_dump($usage / 1024);
    }

    /**
     * 获取目录文件列表
     */
    public function actionGetFileList($path = '/')
    {
        $bucketname = 'xkdemo';
        $username = 'xukun';
        $password = 'xukuntest';
        Yii::import('ext.UpYun');
        $upYun = new UpYun($bucketname, $username, $password);
        if (strncasecmp('/', $path, 1) !== 0) {
            $path = '/' . $path;
        }
        if ($this->isDir($path, $upYun)) {
            var_dump($upYun->getList($path));
        } else {
            throw new CHttpException(500, '不是一个目录');
        }
    }

    //删除空文件夹，有文件的文件夹不允许删除，如果想删除必须清空文件夹，然后删除目录
    public function actionRemoveDir()
    {
        $bucketname = 'xkdemo';
        $username = 'xukun';
        $password = 'xukuntest';
        Yii::import('ext.UpYun');
        $upYun = new UpYun($bucketname, $username, $password);
        var_dump($upYun->rmDir('/test'));
    }

    public function actionCForm()
    {
        $model = new CFormModel;
        $config = array(
            'elements' => array(
                'file' => array(
                    'file'
                ),
            ),
        );
        $form = new CForm($config, $model);
        $this->render('cform', array('form' => $form));
    }

    public function actionGetInfo($file = '/')
    {
        if (strncasecmp('/', $file, 1) !== 0) {
            $file = '/' . $file;
        }
        $bucketname = 'xkdemo';
        $username = 'xukun';
        $password = 'xukuntest';
        Yii::import('ext.UpYun');
        $upYun = new UpYun($bucketname, $username, $password);
        var_dump($upYun->getFileInfo($file));
    }

    /**
     * 删除文件夹及文件,递归删除目录及文件.
     * @param string $path 要递归删除的目录.
     * @param string $bucketname 空间名.
     */
    public function actionRemoveDirQuiet($path = '/', $bucketname = 'xkdemo')
    {
        $bucketname = 'xkdemo'; //空间名.
        $username = 'xukun'; //操作者账号.
        $password = 'xukuntest'; //操作者密码.
        Yii::import('ext.UpYun'); //Yii引入UpYun SDK，记得将upyun.class.php改名为UpYun.php放入extensions目录.
        $upYun = new UpYun($bucketname, $username, $password);
        if (strncasecmp('/', $path, 1) !== 0) {
            $path = '/' . $path;
        }
        if ($this->isDir($path, $upYun)) {//判断是否是一个合法目录，如果不是目录，UpYun会返回一个看不懂的长数组
            $this->removeDir($path, $upYun); //调用删除方法.
        } else {
            throw new CHttpException(500, '不是一个目录');
        }
    }

    /**
     * 删除目录.
     * @param string $path  要删除的目录路径.
     * @param UpYun  $upYun UpYun实例.
     */
    private function removeDir($path, UpYun $upYun)
    {
        $list = $upYun->getList($path); //获取目录列表信息.
        if ($list) {
            foreach ($list as $item) {
                if (strrpos($path, '/') == strlen($path) - 1) {//判断路径是否以/结束，由于开始路径可能是以/结束的，所以这里需要排除一下
                    $file = $path . $item['name'];
                } else {
                    $file = $path . '/' . $item['name'];
                }
                if ($item['type'] == 'folder') {//是文件夹，递归删除子文件夹文件.
                    $this->removeDir($file, $upYun);
                } else {//普通文件，直接删除
                    $upYun->deleteFile($file);
                }
            }
        }
        $upYun->rmDir($path);
    }

    /**
     * 判断文件是否是一个目录，是返回true，否则返回false.
     * @param string $path  要判断的路径.
     * @param UpYun  $upYun UpYun实例.
     * @return boolean
     */
    private function isDir($path = '/', UpYun $upYun)
    {
        if (strncasecmp('/', $path, 1) !== 0) {
            $path = '/' . $path;
        }
        $info = $upYun->getFileInfo($path);
        $type = $info['x-upyun-file-type'];
        if ($type == 'folder') {
            return true;
        } else {
            return false;
        }
    }

    /**
     * 获取一个目录中所有的文件列表.
     * @param string $path       要遍历的目录.
     * @param string $bucketname 空间名.
     * @return null
     */
    public function actionGetFilesList($path = '/', $bucketname = 'xkdemo')
    {
        $bucketname = 'xkdemo'; //空间名.
        $username = 'xukun'; //操作者账号.
        $password = 'xukuntest'; //操作者密码.
        Yii::import('ext.UpYun'); //Yii引入UpYun SDK，记得将upyun.class.php改名为UpYun.php放入extensions目录.
        $upYun = new UpYun($bucketname, $username, $password);
        if (strncasecmp('/', $path, 1) !== 0) {
            $path = '/' . $path;
        }
        if ($this->isDir($path, $upYun)) {//判断是否是一个合法目录，如果不是目录，UpYun会返回一个看不懂的长数组
            $this->glist($path, $list, $upYun); //获取目录列表.
            var_dump($list);
        } else {
            throw new CHttpException(500, '不是一个目录');
        }
    }

    /**
     * 获取目录文件名.
     * @param string $path     要遍历的路径.
     * @param array  $flieList 文件名数组.
     * @param UpYun  $upYun    UpYun实例.
     */
    private function glist($path = '/', &$flieList = array(), UpYun $upYun)
    {
        $list = $upYun->getList($path); //判断目录是否为空.
        if ($list) {
            foreach ($list as $item) {
                if (strrpos($path, '/') == strlen($path) - 1) {//判断路径是否以/结束，由于开始路径可能是以/结束的，所以这里需要排除一下
                    $file = $path . $item['name'];
                } else {
                    $file = $path . '/' . $item['name'];
                }
                if ($item['type'] == 'folder') { //如果是目录，继续遍历子目录.
                    $this->glist($file, $flieList, $upYun);
                } else {
                    $flieList[$path][] = $file; //将文件按照目录归档.
                }
            }
        }
    }

    public function actionReturn($bucket = 'xkdemo', $user_id = 2)
    {
        file_put_contents('/home/xukun/upyun.log', var_export($_REQUEST, true));
        $model = new UserUploadFile();
        $model->user_id = $user_id; //Yii::app()->request->getParam('user_id')
//        $model->file_name = Yii::app()->request->getPost('url');
//        $model->image_type = Yii::app()->request->getPost('image_type', '');
//        $model->upload_time = Yii::app()->request->getPost('time');
//        $model->image_width = Yii::app()->request->getPost('image_width', '');
//        $model->image_height = Yii::app()->request->getPost('image_height', '');
//        $model->sign = Yii::app()->request->getPost('sign');
        $model->file_name =  Yii::app()->request->getParam('url');
        $model->image_type = Yii::app()->request->getParam('image_type', '');
        $model->upload_time = Yii::app()->request->getParam('time');
        $model->image_width = Yii::app()->request->getParam('image_width', '');
        $model->image_height = Yii::app()->request->getParam('image_height', '');
        $model->sign = Yii::app()->request->getParam('sign');
        $model->bucket = $bucket;
        if ($model->save()) {
            echo '插入成功，插入后的id是:' . $model->id;
            sleep(3);
            $url = Yii::app()->createUrl($this->id . '/forms', array());
            $this->redirect($url);
        } else {
            var_dump($model->getErrors());
        }
    }

    //使用bootstrap创建上传表单
    public function actionBS()
    {
        $model = new UserUploadFile;
        $data = array('model' => $model);
        $this->render('bs', $data);
    }

}
